/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ClasificacionDePizzasMedianFilterBox.java
 *
 * Created on 26-dic-2009, 15:20:24
 */
package clasificaciondepizzas;

import clasificaciondepizzas.models.BaseModel;
import com.sun.media.jai.widget.DisplayJAI;
import javax.media.jai.PlanarImage;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import clasificaciondepizzas.operations.ImageOperations;
import clasificaciondepizzas.types.images.ImageType;

/**
 *
 * @author Manuel
 */
public class ClasificacionDePizzasMedianFilterBox extends javax.swing.JDialog {

    /** Creates new form ClasificacionDePizzasMedianFilterBox */
    public ClasificacionDePizzasMedianFilterBox(java.awt.Frame parent) {
        super(parent);
        initComponents();
    }

    public void showThresholdBox(ImageType type) {
        JFrame mainFrame = ClasificacionDePizzasApp.getApplication().getMainFrame();
        thresholdBox = new ClasificacionDePizzasThresholdBox(mainFrame);
        thresholdBox.setLocationRelativeTo(this);
        image = ImageOperations.medianFilter(image, medianSlider.getValue());
        thresholdBox.setImage(image);
        thresholdBox.setBaseModel(bm);
        thresholdBox.setImageType(type);

        ClasificacionDePizzasApp.getApplication().show(thresholdBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        medianImageScrollPane = new javax.swing.JScrollPane();
        acceptButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        medianSlider = new javax.swing.JSlider();
        levelLabel = new javax.swing.JLabel();
        radiusTextField = new javax.swing.JTextField();
        pixelsLabel = new javax.swing.JLabel();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(clasificaciondepizzas.ClasificacionDePizzasApp.class).getContext().getResourceMap(ClasificacionDePizzasMedianFilterBox.class);
        setTitle(resourceMap.getString("medianFilterBox.title")); // NOI18N
        setModalityType(java.awt.Dialog.ModalityType.APPLICATION_MODAL);
        setName("medianFilterBox"); // NOI18N
        setResizable(false);

        medianImageScrollPane.setViewportBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("medianImageScrollPane.viewportBorder.title"))); // NOI18N
        medianImageScrollPane.setName("medianImageScrollPane"); // NOI18N

        acceptButton.setText(resourceMap.getString("acceptButton.text")); // NOI18N
        acceptButton.setName("acceptButton"); // NOI18N
        acceptButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                acceptButtonActionPerformed(evt);
            }
        });

        cancelButton.setText(resourceMap.getString("cancelButton.text")); // NOI18N
        cancelButton.setName("cancelButton"); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        medianSlider.setMajorTickSpacing(100);
        medianSlider.setMinimum(1);
        medianSlider.setMinorTickSpacing(1);
        medianSlider.setPaintLabels(true);
        medianSlider.setSnapToTicks(true);
        medianSlider.setValue(3);
        medianSlider.setName("medianSlider"); // NOI18N
        medianSlider.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                medianSliderMouseReleased(evt);
            }
        });
        medianSlider.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                medianSliderStateChanged(evt);
            }
        });

        levelLabel.setText(resourceMap.getString("levelLabel.text")); // NOI18N
        levelLabel.setName("levelLabel"); // NOI18N

        radiusTextField.setText(((Integer)medianSlider.getValue()).toString());
        radiusTextField.setName("radiusTextField"); // NOI18N
        radiusTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radiusTextFieldActionPerformed(evt);
            }
        });

        pixelsLabel.setText(resourceMap.getString("pixelsLabel.text")); // NOI18N
        pixelsLabel.setName("pixelsLabel"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(206, 206, 206)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(radiusTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(pixelsLabel))
                            .addComponent(levelLabel)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(medianImageScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
                            .addComponent(medianSlider, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(cancelButton)
                            .addComponent(acceptButton))))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {acceptButton, cancelButton});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {levelLabel, radiusTextField});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(medianImageScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(acceptButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(medianSlider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(levelLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(radiusTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(pixelsLabel))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void medianSliderStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_medianSliderStateChanged
        radiusTextField.setText(((Integer) medianSlider.getValue()).toString());
}//GEN-LAST:event_medianSliderStateChanged

    private void radiusTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radiusTextFieldActionPerformed
        PlanarImage previewImage; //previsualización en miniatura con el filtro aplicado
        int value = Integer.parseInt(radiusTextField.getText()); // valor del campo de texto

        // el control de desplazamiento se actualiza junto con el campo de texto
        medianSlider.setValue(value);

        try {
            // previsualización en miniatura del filtro de la mediana
            previewImage = ImageOperations.medianFilter(thumbnail, medianSlider.getValue());
            DisplayJAI display = new DisplayJAI(previewImage);
            medianImageScrollPane.setViewportView(display);
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible aplicar el filtro de la mediana.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        } catch (RuntimeException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible previsualizar la imagen.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
}//GEN-LAST:event_radiusTextFieldActionPerformed

    private void medianSliderMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_medianSliderMouseReleased
        PlanarImage previewImage; //previsualización en miniatura con el filtro aplicado

        try {
            // previsualización en miniatura del filtro de la mediana
            previewImage = ImageOperations.medianFilter(thumbnail, medianSlider.getValue());
            DisplayJAI display = new DisplayJAI(previewImage);
            medianImageScrollPane.setViewportView(display);
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible aplicar el filtro de la mediana.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        } catch (RuntimeException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible previsualizar la imagen.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_medianSliderMouseReleased

    private void acceptButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_acceptButtonActionPerformed
        setVisible(false);
        showThresholdBox(ImageType.BASE);
        dispose();
    }//GEN-LAST:event_acceptButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton acceptButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel levelLabel;
    private javax.swing.JScrollPane medianImageScrollPane;
    private javax.swing.JSlider medianSlider;
    private javax.swing.JLabel pixelsLabel;
    private javax.swing.JTextField radiusTextField;
    // End of variables declaration//GEN-END:variables
    private ClasificacionDePizzasThresholdBox thresholdBox;
    protected PlanarImage image;
    protected PlanarImage thumbnail;
    private BaseModel bm;

    /**
     * Devuelve el valor de image
     *
     * @return el valor de image
     */
    public PlanarImage getImage() {
        return image;
    }

    /**
     * Establece el valor de image
     *
     * @param image nuevo valor de image
     */
    public void setImage(PlanarImage image) {
        this.image = image;
        thumbnail = this.image;
        PlanarImage previewImage; //previsualización en miniatura con el filtro aplicado

        // si la imagen supera el tamaño del panel con desplazamiento se escala a un tamaño menor
        if (image.getWidth() > medianImageScrollPane.getWidth() || image.getHeight() > medianImageScrollPane.getHeight()) {
            // si la imagen supera la anchura del panel con desplazamiento se escala a una anchura menor
            if (image.getWidth() > image.getHeight()) {
                float ratio = (float) medianImageScrollPane.getWidth() / (float) image.getWidth();
                thumbnail = ImageOperations.scale(image, ratio, ratio);
            } // si la imagen supera la altura del panel con desplazamiento se escala a una altura menor
            else {
                float ratio = (float) medianImageScrollPane.getHeight() / (float) image.getHeight();
                thumbnail = ImageOperations.scale(image, ratio, ratio);
            }
        }


        try {
            // previsualización en miniatura del filtro de la mediana
            previewImage = ImageOperations.medianFilter(thumbnail, medianSlider.getValue());
            DisplayJAI display = new DisplayJAI(previewImage);
            medianImageScrollPane.setViewportView(display);
        } catch (IllegalArgumentException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible aplicar el filtro de la mediana.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        } catch (RuntimeException e) {
            JOptionPane.showMessageDialog(this,
                    "No es posible previsualizar la imagen.",
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    void setBaseModel(BaseModel bm) {
        this.bm = bm;
    }
}
